package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.config.CartInterceptor;
import com.atguigu.gulimall.cart.feign.ProductCartFeignService;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.to.UserInfoTo;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @Classname CartServiceImpl
 * @Description TODO
 * @Date 2021/9/24 11:30
 * @Author Anonymous
 */
@SuppressWarnings("all")
@Service
@Slf4j
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductCartFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    private static final String CART_PREFIX = "gulimall:cart";

    /**
     * 向购物车添加数据
     */
    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        System.out.println("==============================" + executor);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        //判断Redis是否有该商品的信息
        String productRedisValue = (String) cartOps.get(skuId.toString());

        if (StringUtils.isEmpty(productRedisValue)) {
            //2、添加新的商品到购物车(redis)
            CartItem cartItemVo = new CartItem();
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                //1、远程查询当前要添加的商品的信息
                R info = productFeignService.info(skuId);
                SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItemVo.setCheck(true);
                cartItemVo.setSkuId(skuInfo.getSkuId());
                cartItemVo.setTitle(skuInfo.getSkuTitle());
                cartItemVo.setImage(skuInfo.getSkuDefaultImg());
                cartItemVo.setPrice(skuInfo.getPrice());
                cartItemVo.setCount(num);
            }, executor);


            //开启第二个异步任务
            CompletableFuture<Void> getSkuAttrValuesFuture = CompletableFuture.runAsync(() -> {
                //2、远程查询skuAttrValues组合信息
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItemVo.setSkuAttr(skuSaleAttrValues);
            }, executor);

            //等待所有的异步任务全部完成
            CompletableFuture.allOf(getSkuInfoTask, getSkuAttrValuesFuture).get();

            String cartItemJson = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(), cartItemJson);
            return cartItemVo;
        } else {
            //如果redis中已经有购物车的数据，直接加数量就可以了
            CartItem cartItem = JSON.parseObject(productRedisValue, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            //修改redis的数据
            String cartItemJson = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), cartItemJson);
            return cartItem;
        }
    }

    /**
     * 获取购物项
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        String cartItemJson = (String) getCartOps().get(skuId.toString());
        CartItem cartItem = JSON.parseObject(cartItemJson, CartItem.class);
        return cartItem;
    }

    /**
     * 获取用户登录或者未登录购物车里所有的数据
     *
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null) {
            //登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            //如果临时购物车有数据，要进行合并
            List<CartItem> cartItems1 = getCartItems(tempCartKey);
            if (cartItems1 != null) {
                //说明临时购物车有数据
                for (CartItem cartItem : cartItems1) {
                    //将临时购物车加入到已经登录的用户䣌购物车中
                    addToCart(cartItem.getSkuId(), cartItem.getCount());
                }
            }
            //将临时购物车中的数据清空
            clearCartInfo(tempCartKey);
            //获取登录后的购物车数据【包含合并过来的临时购物车的数据和登录后购物车的数据】
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        } else {
            //未登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;
    }

    @Override
    public void clearCartInfo(String key) {
        redisTemplate.delete(key);
    }

    /**
     * 商品是否选中
     */
    @Override
    public void checkItem(Long skuId, Integer checked) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(checked == 1 ? true : false);
        //保存到redis
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    /**
     * 改变商品数量
     */
    @Override
    public void changeItemCount(Long skuId, Integer num) {
        //查询购物车里面的商品
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //序列化存入redis中
        String redisValue = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), redisValue);

    }

    /**
     * 删除购物车中的数据
     */
    @Override
    public void deleteIdCartInfo(Integer skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }


    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null) {
            //说明没有登录
            return null;
        } else {
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            //得到购物项之后，要筛选出被选中的购物项
            List<CartItem> collect = cartItems.stream()
                    .map(cartItem -> {
                        //要将购物车中的价格设置成最新价格
                        R price = productFeignService.getPrice(cartItem.getSkuId());
                        String data = (String) price.get("data");
                        cartItem.setPrice(new BigDecimal(data));
                        return cartItem;
                    })
                    .filter(item -> {
                        return item.getCheck();
                    }).collect(Collectors.toList());
            return collect;
        }
    }

    /**
     * 获取购物车里面的数据
     *
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(String cartKey) {
        //获取购物车里面的所有商品
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();//得到所有的值
        if (values != null && values.size() > 0) {
            return values.stream().map((obj) -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 获取到我们要操作的购物车
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        //得到用户信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //1、判断是向离线购物车中添加数据还是登录后的购物车中添加数据
        String cartKey = "";//相当于redis以后增删改查哪个购物车，就增删改查这个键
        if (userInfoTo.getUserId() != null) {
            //说明已经登录，就要操作登录的购物车
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            //没有登录，就用临时购物车
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        //操作固定的key
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }
}
